package com.youdianda.config;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.youdianda.common.BaseContext;
import com.youdianda.common.CustomException;
import com.youdianda.until.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Configuration
public class TokenConfig implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("x-token");
        if (StrUtil.isBlank(token)) {
            throw new CustomException("token无效");
        }
        Claims claims = AppJwtUtil.getClaimsBody(token);
        int flag = AppJwtUtil.verifyToken(claims);
        if (flag == 1 || flag == 2) {
            throw new CustomException("token已失效");
        }

        Object id = claims.get("id");
        BaseContext.setCurrentId(Convert.toLong(id));
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        BaseContext.threadLocalClose();
    }
}
